import { Button, List, DatePicker, NavBar, Popup, Toast, Dialog } from 'antd-mobile'
import classNames from 'classnames'
import { getUserProfile, updateUserProfile } from '@/store/actions/profile'
import styles from './index.module.scss'
import useInitialState from '@/hooks/useInitialState'
import { useState } from 'react'
import EditInput from './EditInput'
import { useDispatch } from 'react-redux'

import { logout } from '@/store/actions/login'
import { useHistory } from 'react-router-dom'
const Item = List.Item
type InputState = {
  visible: boolean,
  type: '' | 'name' | 'intro' // 当前编辑的内容
}
const formatDate = (value: Date) => {
  const year = value.getFullYear()
  let month:number | string = value.getMonth() + 1 // 2 ===> 02
  month = month > 9 ? month : ('0' + month.toString())
  let date :number | string = value.getDate()
  date = date > 9 ? date : ('0' + date.toString())
  const d = [year, month, date].join('-')
  return d
}

const ProfileEdit = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const [showBirthday, setShowBirthday] = useState(false)

  const [showInput, setShowInput] = useState<InputState>({ type: '', visible: false })
  const { userProfile } = useInitialState(getUserProfile, 'profile')

  // 隐藏弹层
  const hideInput = () => { setShowInput({ visible: false, type: '' }) }

  // 执行具体的修改动作
  const onUpdate = async (type: '' | 'name' | 'intro', value:string) => {
    console.log('要修改', type, '改成', value)
    try {
      // 1. 发送请求，修改数据
      await dispatch(updateUserProfile(type, value))
      Toast.show({
        content: '修改成功'
      })
      // 2. 关闭弹层
      hideInput()
    } catch (err) {
      Toast.show({
        content: '修改失败'
      })
    }
  }

  const onBirthHide = () => { setShowBirthday(false) }
  const onUpdateBirthday = async (value: Date) => {
    const d = formatDate(value)
    // 1. 调用接口，修改生日

    // 2. 隐藏弹框
    try {
      // 1. 发送请求，修改数据
      await dispatch(updateUserProfile('birthday', d))
      Toast.show({
        content: '修改成功'
      })
      // 2. 关闭弹层
      onBirthHide()
    } catch (err) {
      Toast.show({
        content: '修改失败'
      })
    }
  }

  const onQuit = () => {
    // 1. 弹框，确认是否退出
    Dialog.confirm({
      content: '是否退出',
      onConfirm: async () => {
        // 1. 清空数据

        dispatch(logout())
        // 2. 提示
        Toast.show({
          icon: 'success',
          content: '退出成功',
          position: 'bottom'
        })
        // 3. 页面跳转
        history.push('/login')
      }
    })

    // Dialog.show({
    //   content: '确认退出吗',
    //   closeOnAction: true,
    //   actions: [
    //     [
    //       {
    //         key: 'cancel',
    //         text: '取消',
    //       },
    //       {
    //         key: 'delete',
    //         text: '确认',
    //         bold: true,
    //         danger: true,
    //         style: {
    //           color: 'var(--adm-color-weak)'
    //         }
    //       },
    //     ],
    //   ],
    // })
  }

  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar
          style={{
            '--border-bottom': '1px solid #F0F0F0'
          }}
        >
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              extra={
                <span className="avatar-wrapper">
                  <img
                    width={24}
                    height={24}
                    src={userProfile.photo}
                    alt=""
                  />
                </span>
              }
              arrow
            >
              头像
            </Item>
            <Item onClick={() => { setShowInput({ type: 'name', visible: true }) }} arrow extra={userProfile.name}>
              昵称
            </Item>
            <Item
              onClick={() => { setShowInput({ type: 'intro', visible: true }) }}
              arrow
              extra={
                <span className={classNames('intro', 'normal')}>
                  {userProfile.intro}
                </span>
              }
            >
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item arrow extra={ userProfile.gender ? '男' : '女'}>
              性别
            </Item>
            <Item arrow extra={userProfile.birthday} onClick={() => { setShowBirthday(true) }}>
              生日
            </Item>
          </List>

          <DatePicker
            visible={false}
            value={new Date()}
            title="选择年月日"
            min={new Date(1900, 0, 1, 0, 0, 0)}
            max={new Date()}
          />
        </div>

        <div className="logout">
          <Button className="btn" onClick={onQuit}>退出登录</Button>
        </div>
      </div>
      <Popup
      visible={showInput.visible}
      position='right'
      destroyOnClose
      >
        <EditInput type={showInput.type} hideInput={hideInput} onUpdate={onUpdate}/>
      </Popup>

      {/* 日期选择器 */}
      <DatePicker
        visible={showBirthday}
        value={new Date(userProfile.birthday)}
        onCancel={onBirthHide}
        onConfirm={onUpdateBirthday}
        title="修改生日"
        max={new Date()}
        min={new Date('1900-01-01')}
        />
    </div>

  )
}

export default ProfileEdit
